type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';

const BASE_URL = 'https://jsonplaceholder.typicode.com';

export default {
  async request<T>(
    method: HttpMethod,
    url: string,
    data?: unknown
  ): Promise<T> {
    const fullUrl = url.startsWith('/') ? `${BASE_URL}${url}` : url;

    const config: RequestInit = {
      method,
      headers: { 'Content-Type': 'application/json' },
    };

    if (data) {
      config.body = JSON.stringify(data);
    }

    try {
      const response = await fetch(fullUrl, config);

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      return response.json() as Promise<T>;
    } catch (error) {
      console.error('Request failed:', error);
      throw error;
    }
  },

  get<T>(url: string): Promise<T> {
    return this.request<T>('GET', url);
  },

  post<T>(url: string, data?: unknown): Promise<T> {
    return this.request<T>('POST', url, data);
  },

  put<T>(url: string, data?: unknown): Promise<T> {
    return this.request<T>('PUT', url, data);
  },

  delete<T>(url: string): Promise<T> {
    return this.request<T>('DELETE', url);
  }
};